package com.qf.service.impl;

import com.qf.constant.RabbitMQConstants;
import com.qf.model.StandardSubmit;
import com.qf.service.FilterChainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 路由策略
 * 创建队列：
 *   1、Java配置类   启动类一执行就已经加载了
 *       @Bean   队列
 *       public Queue queue(变量){
 *           return QueueBuilder.dru..("sms_send_gateway_1").build()
 *       }
 *   2、注解   启动类一执行就已经加载了  马上去监听 没有队列 就创建
 *       @RabbitListener(bindings = @QueueBinding(
 *             exchange = @Exchange(value = RabbitMQConstants.TOPIC_PRE_SEND_EXCHANGE,type = "topic"),
 *             value = @Queue(value = "sms_send_gateway_"+ 变量,durable = "true",autoDelete = "false"),
 *             key = {RabbitMQConstants.BINDING}// sms
 *     ))
 *   3、动态创建队列
 *     根据不能条件当场 创建队列
 *      @Autowired
 *     private AmqpAdmin amqpAdmin; Java代码直接操作基于AMQP协议的管理员
 *       guest
 *       guest
 *
 *
 * @author zhaojian
 */
@Service(value = "router")
@Slf4j
public class RouterFilterServiceImpl implements FilterChainService {

    @Autowired
    private AmqpAdmin amqpAdmin;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * **路由 ：**从客户通道表中选择所配的通道下发
     *
     * - 如果找不到通道把发送日志存到Elasticsearch
     * - 如果同时是HTTP的发送方式就模拟出状态报告推送给客户
     * @param submit
     * @return
     */
    @Override
    public boolean strategy(StandardSubmit submit) {
        try {
            //1:下发网关ID  通道ID
            Integer gatewayID = submit.getGatewayID();
            //2: 路由到不同的运营商   RabbitMQ :   队列：sms_send_gateway_1  代表：移动
            //2: 路由到不同的运营商   RabbitMQ :   队列：sms_send_gateway_2  代表：联通
            //2: 路由到不同的运营商   RabbitMQ :   队列：sms_send_gateway_3  代表：电信
            //2: 路由到不同的运营商   RabbitMQ :   队列：sms_send_gateway_4  代表：未知
            String queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + gatewayID;
            //3:创建队列  声明队列
            amqpAdmin.declareQueue(QueueBuilder.durable(queueName).build());
            //4:发送消息  默认交换机-->默认routingkey--> 声明队列
            rabbitTemplate.convertAndSend(queueName,submit);
        } catch (Exception e) {
            //throw new RuntimeException(e);
            //路由失败
            return false;
        }
        //路由成功
        return true;
    }
}